<?php
/**
 * AJAX自动同步接口
 * 处理普通账号角色的自动同步
 */

// 错误报告设置 - 关闭显示错误，避免HTML输出
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// 设置响应头 - 必须在任何输出之前
header('Content-Type: application/json; charset=utf-8');

// 开启会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
    echo json_encode([
        'success' => false,
        'error' => '用户未登录'
    ]);
    exit();
}

// 数据库连接
try {
    if (!file_exists('database.php')) {
        throw new Exception("database.php文件不存在");
    }

    require_once 'database.php';

    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("数据库连接失败");
    }

    if (!$conn->ping()) {
        throw new Exception("数据库连接已断开");
    }

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => '数据库连接失败：' . $e->getMessage()
    ]);
    exit();
}

// 只处理POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        'success' => false,
        'error' => '只支持POST请求'
    ]);
    exit();
}

try {
    // 获取员工数据
    $staff_sql = "SELECT user_id, name, serving FROM staff ORDER BY user_id";
    $staff_result = $conn->query($staff_sql);

    if (!$staff_result) {
        throw new Exception("获取员工数据失败: " . $conn->error);
    }

    $staff_data = [];
    while ($row = $staff_result->fetch_assoc()) {
        $staff_data[$row['user_id']] = [
            'name' => $row['name'],
            'serving' => intval($row['serving'])
        ];
    }

    // 获取用户角色数据
    $roles_sql = "SELECT user_id, role FROM user_roles";
    $roles_result = $conn->query($roles_sql);

    if (!$roles_result) {
        throw new Exception("获取角色数据失败: " . $conn->error);
    }

    $user_roles = [];
    while ($row = $roles_result->fetch_assoc()) {
        $user_id = $row['user_id'];
        if (!isset($user_roles[$user_id])) {
            $user_roles[$user_id] = [];
        }
        $user_roles[$user_id][] = $row['role'];
    }

    // 检测需要同步的记录
    $updates_needed = [];
    foreach ($staff_data as $user_id => $staff) {
        $current_roles = $user_roles[$user_id] ?? [];
        $has_regular_role = in_array('普通账号', $current_roles);
        $serving = $staff['serving'];

        if ($serving === 1 && !$has_regular_role) {
            // 在职员工应该有普通账号角色
            $updates_needed[] = [
                'action' => 'add',
                'user_id' => $user_id,
                'role' => '普通账号'
            ];
        } elseif ($serving === 0 && $has_regular_role) {
            // 离职员工不应该有普通账号角色
            $updates_needed[] = [
                'action' => 'remove',
                'user_id' => $user_id,
                'role' => '普通账号'
            ];
        }
    }

    if (empty($updates_needed)) {
        echo json_encode([
            'success' => true,
            'count' => 0,
            'message' => '所有普通账号角色已同步，无需处理'
        ]);
        exit();
    }

    // 执行同步操作
    $conn->begin_transaction();

    $processed_count = 0;
    $current_user = $_SESSION['user_id'];

    foreach ($updates_needed as $update) {
        if ($update['action'] === 'add') {
            $sql = "INSERT INTO user_roles (user_id, role, assigned_by, assigned_at) VALUES (?, ?, ?, NOW())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sss", $update['user_id'], $update['role'], $current_user);

            if ($stmt->execute()) {
                $processed_count++;
            }

        } elseif ($update['action'] === 'remove') {
            $sql = "DELETE FROM user_roles WHERE user_id = ? AND role = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $update['user_id'], $update['role']);

            if ($stmt->execute()) {
                $processed_count++;
            }
        }
    }

    $conn->commit();

    echo json_encode([
        'success' => true,
        'count' => $processed_count,
        'message' => "成功同步 {$processed_count} 条普通账号角色记录"
    ]);

} catch (Exception $e) {
    // 回滚事务
    if (isset($conn) && $conn->inTransaction) {
        $conn->rollback();
    }

    // 记录错误日志
    error_log("自动同步错误: " . $e->getMessage());

    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

// 关闭数据库连接
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}
?>